package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    // 发布动态
    public void publish(Movement movement) {
        try {
            // 1:保存动态详情   需要设置pid,设置发布时间
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            /*// 2:查询当前用户的好友数据
            Criteria criteria = Criteria.where("userId").is(movement.getUserId());
            Query query = Query.query(criteria);
            // 查询的是多条,需要一个集合接收
            List<Friend> friends = mongoTemplate.find(query, Friend.class);
            // 3:循环好友数据,构建时间线数据存入数据库
            for (Friend friend : friends) {
                MovementTimeLine timeLine = new MovementTimeLine();
                timeLine.setMovementId(movement.getId());
                timeLine.setUserId(friend.getUserId());
                timeLine.setFriendId(friend.getFriendId());
                timeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.save(timeLine);
            }*/
            timeLineService.saveTimeLin(movement.getUserId(),movement.getId());
        }catch (Exception e){
            // 忽略事务处理
            e.printStackTrace();
        }
    }

    // 根据用户id,查询此用户发布的动态数据列表
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        // 构建Criteria对象,使用mongoTemplate进行分页查询
        Criteria criteria = new Criteria("userId").is(userId);
        Query query = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0L,list);
    }

    // 根据当前操作用户id,查询用户好友发布的动态列表
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long friendId) {
        // 1:根据friendId查询时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        // 查询时间线表数据
        List<MovementTimeLine> timeLines = mongoTemplate.find(query, MovementTimeLine.class);
        // 2:提取动态id列表
        List<ObjectId> list = CollUtil.getFieldValues(timeLines,"movementId", ObjectId.class);
        // 3:根据动态id查询动态详情
        Query qy = Query.query(Criteria.where("id").in(list));
        return mongoTemplate.find(qy,Movement.class);
    }

    // 随机获取多条动态数据
    public List<Movement> randomMovements(Integer counts) {
        // 1:创建统计对象,设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        // 2:调用mongoTemplate方法进行统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        // 3:获取统计结果
        return results.getMappedResults();
    }

    // 根据pid数组查询动态
    public List<Movement> findMovementsPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query,Movement.class);
    }

    // 根据id查询动态详情
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }
}
